package com.cloud.yxn.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.cloud.common.to.es.SkuEsTo;
import com.cloud.yxn.search.config.ElasticSearchConfig;
import com.cloud.yxn.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lisw
 * @create 2021/7/3 11:13
 */
@Service("productSaveService")
@Slf4j
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    private RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsTo> skuEsToList) throws IOException {
        //1、建立product对应索引
        //2、操作es保存数据
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsTo skuEsTo : skuEsToList) {
            IndexRequest indexRequest = new IndexRequest("product");
            indexRequest.id(skuEsTo.getSkuId().toString());
            String json = JSON.toJSONString(skuEsTo);
            indexRequest.source(json, XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, ElasticSearchConfig.COMMON_OPTIONS);
        //todo 如果批量出现错误
        List<String> collect = Arrays.stream(bulk.getItems()).map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        log.info("商品上架完成的是:{}",collect);
        boolean b = bulk.hasFailures();
        if (b){
            log.error("商品上架错误{}",collect);
        }
        return b;
    }
}
